package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security框架自动调用UserDetailsServiceImpl中的loadUserByUsername方法，参数：{}", s);
        //从数据库中根据用户名查询用户信息
        AdminLoginInfoVO info = adminMapper.getAdminInfoByUsername(s);
        log.debug("从数据库中根据用户名【{}】查询管理员信息，结果：{}", s, info);
        //若查询出来为null, 则抛出异常或返回null
        if (info == null) {
            log.debug("没有与用户名【{}】匹配的管理员信息，即将抛出BadCredentialsException", s);
            throw new BadCredentialsException("登录失败, 用户不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : info.getPermissions()) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        AdminDetails adminDetails = new AdminDetails(
                info.getId(),
                info.getUsername(),
                info.getPassword(),
                info.getEnable() == 1,
                authorities
        );


        //若查询出来不为null, 则将查询到的用户信息撞到UserDetails类型的对象中返回, 接下来框架会完成认证过程
//        UserDetails userDetails = User.builder()
//                .username(s)
//                .password(info.getPassword())
//                .disabled(info.getEnable() == 0)
//                .accountLocked(false)       //账号锁定, 此项目没有该机制
//                .accountExpired(false)      //账号过期, 此项目没有该机制
//                .authorities("暂时给一个山寨权限标识")     //权限
//                .build();
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", adminDetails);
        return adminDetails;
    }
}
